package com.atXiao.video.websocket;

import cn.hutool.core.util.StrUtil;
import com.atXiao.video.utils.ChatGptUntil;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;

@ServerEndpoint(value = "/websocket/{ConversionId}")
@Component
public class WebSocket {

    private static ChatGptUntil chatGptUntil;





    @Resource
    public void setChatGptUntil(ChatGptUntil chatGptUntil) {
        WebSocket.chatGptUntil = chatGptUntil;
    }

    private final static Logger logger = LogManager.getLogger(WebSocket.class);

    /**
     * 静态变量，用来记录当前在线连接数。应该把它设计成线程安全的
     */

    private static int onlineCount = 0;

    /**
     * concurrent包的线程安全Map，用来存放每个客户端对应的MyWebSocket对象
     */
    private static ConcurrentHashMap<String, WebSocket> webSocketMap = new ConcurrentHashMap<>();

    /**
     * 与某个客户端的连接会话，需要通过它来给客户端发送数据
     */

    private Session session;
    private Long ConversionId;


    /**
     * 通过userId向客户端发送消息
     */
    public void sendMessageByUserId(Long ConversionId, String message) throws IOException {
        logger.info("服务端发送消息到{},消息：{}", ConversionId, message);
        if (StrUtil.isNotBlank(ConversionId.toString()) && webSocketMap.containsKey(ConversionId.toString())) {
            webSocketMap.get(ConversionId.toString()).sendMessage(message);
        } else {
            logger.error("{}不在线", ConversionId);
        }

    }

    /**
     * 向客户端发送消息
     */
    public void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
    }



    public static synchronized int getOnlineCount() {
        return onlineCount;
    }

    public static synchronized void addOnlineCount() {
        WebSocket.onlineCount++;
    }

    public static synchronized void subOnlineCount() {
        WebSocket.onlineCount--;
    }

}
